package net.qhzw.vip.qiyu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import net.qhzw.vip.qiyu.dto.DeliveryManDto;
import net.qhzw.vip.qiyu.entity.Area;
import net.qhzw.vip.qiyu.mapper.AreaMapper;
import net.qhzw.vip.qiyu.service.AreaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class AreaServiceImpl extends ServiceImpl<AreaMapper, Area> implements AreaService {

    @Autowired
    private AreaMapper areaMapper;

    @Override
    @Cacheable(cacheNames = "area", key = "#pid")
    public List<Area> listByPid(Long pid) {
        return areaMapper.selectList(new LambdaQueryWrapper<Area>().eq(Area::getParentId, pid));
    }

    @Override
    @CacheEvict(cacheNames = "area", key = "#pid")
    public void removeAreaCacheByParentId(Long pid) {

    }

    @Override
    public Area getByAreaName(String areaName) {
        return areaMapper.selectByAreaName(areaName);
    }

    @Override
    public List<Area> getAreaParentById(Long areaId) {
        return areaMapper.selectAreaParentById(areaId);
    }

    @Override
    public Area getAreaById(Long areaId) {
        return areaMapper.selectAreaById(areaId);
    }

    @Override
    public List<Long> srchAllChildrenIdByPid(Long pid) {
        return areaMapper.srchAllChildrenIdByPid(pid);
    }


    /**
     * 根据pid查询所有的孩子节点
     *
     * @param pid
     * @return
     */
    @Override
    public Area findChildsByPid(Long pid) {
        Area rootArea = getById(pid);
        if (rootArea != null) {
            List<Area> areas = areaMapper.selectChildsByPid(pid);
            if (!CollectionUtils.isEmpty(areas)) {
                rootArea.setAreaChilds(getChildAreas(rootArea.getAreaId(), areas));
            }
        }
        return rootArea;
    }

    @Override
    public List<DeliveryManDto> deliveryPntRgn(Integer isVip) {
        return areaMapper.selectDeliveryPntRgn(isVip);
    }


    /**
     * 递归遍历所有的孩子
     *
     * @param parentId
     * @param areas
     * @return
     */
    private List<Area> getChildAreas(Long parentId, List<Area> areas) {
        List<Area> childs = new ArrayList<>();
        for (Area area : areas) {
            if (area.getParentId().equals(parentId)) { // 找儿子
                childs.add(area);
                area.setAreaChilds(getChildAreas(area.getAreaId(), areas)); // 给该儿子设置儿子
            }
        }
        return childs;
    }

}
